#include "StdAfx.h"
#include "ConectionEventHandler.h"
#include "RdcTransport.h"

rdc_transport::ConectionEventHandler::ConectionEventHandler()
{
    signals.insert(CHANNEL_EVENT_INITIALIZED, std::auto_ptr<signal_t>(new signal_t));
    signals.insert(CHANNEL_EVENT_CONNECTED, std::auto_ptr<signal_t>(new signal_t));
    signals.insert(CHANNEL_EVENT_V1_CONNECTED, std::auto_ptr<signal_t>(new signal_t));
    signals.insert(CHANNEL_EVENT_DISCONNECTED, std::auto_ptr<signal_t>(new signal_t));
    signals.insert(CHANNEL_EVENT_TERMINATED, std::auto_ptr<signal_t>(new signal_t));
}

boost::signal<void(LPVOID, LPVOID, UINT)> & 
rdc_transport::ConectionEventHandler::OnEvent(UINT event)
{
    boost::ptr_map<UINT, signal_t>::iterator it = signals.find(event);
    assert(it != signals.end());

    return *it->second;
}


void rdc_transport::ConectionEventHandler::Register(connectionEventDelegate& handler, UINT event)
{
    boost::ptr_map<UINT, signal_t>::iterator it = signals.find(event);
    if(it == signals.end())
        throw std::runtime_error(std::string(__FUNCTION__) + "Cannot find event");

    it->second->connect(handler);
}

void rdc_transport::ConectionEventHandler::RegisterHandlers(connectionEventDelegate onConnect, connectionEventDelegate onDisconnect, connectionEventDelegate onTerminate)
{
    Register(onConnect, CHANNEL_EVENT_CONNECTED);
    Register(onDisconnect, CHANNEL_EVENT_DISCONNECTED);
    Register(onTerminate, CHANNEL_EVENT_TERMINATED);
    Register(onTerminate, CHANNEL_EVENT_V1_CONNECTED);
}